package org.gangcai.mac.shop.activity;

import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.allen.library.SuperTextView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.bean.EveryDayBean;
import org.gangcai.mac.shop.bean.GetPartMoneyBean;
import org.gangcai.mac.shop.bean.OrderDetailBean;
import org.gangcai.mac.shop.bean.ReBean;
import org.gangcai.mac.shop.common.MultiStatusActivity;
import org.gangcai.mac.shop.constants.Constant;
import org.gangcai.mac.shop.manager.RetrofitManager;
import org.gangcai.mac.shop.oberver.CommonObserver;
import org.gangcai.mac.shop.responsibility.DataResponsibility;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.mayubao.pay_library.AliPayReq2;
import io.github.mayubao.pay_library.PayAPI;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;

public class BillDetailActivity extends MultiStatusActivity {

    @BindView(R.id.goodImage)
    ImageView goodImage;
    @BindView(R.id.goodTitle)
    TextView goodTitle;
    @BindView(R.id.timeTips)
    TextView timeTips;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.goodMoney)
    TextView goodMoney;
    @BindView(R.id.yiyuqi)
    TextView yiyuqi;
    @BindView(R.id.hkzr)
    TextView hkzr;
    @BindView(R.id.moneyall)
    TextView moneyall;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.yuqiTips)
    TextView yuqiTips;
    @BindView(R.id.cardView)
    CardView cardView;
    @BindView(R.id.huankuan)
    SuperButton huankuan;
    @BindView(R.id.abc)
    LinearLayout abc;
    /**
     * 分割线,太丑
     */
    @BindView(R.id.eft)
    View eft;
    private String order_id;
    private ArrayList<EveryDayBean.InfoBean> dataList;
    private CommonAdapter<EveryDayBean.InfoBean> adapter;
    private OrderDetailBean mValue;
    private String title;
    private String payType = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        order_id = extras.getString("order_id");
        title = extras.getString("title");
        //支付类型
        //当支付类型是支付宝支付,不需要展示还款样式
        //默认非支付宝支付方式
        payType = extras.getString("payType");

        if (TextUtils.isEmpty(title)) {
            title = "账单详情";
        }
        initTitleBarView(titlebar, title);

        ButterKnife.bind(this);
        initView();
        loadData();
    }

   /* private void getList() {
        RetrofitManager.getInstance().create(AppAPI.class)
                .everyDayPay(mValue.getStage_id())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io()).subscribe(new CommonObserver<EveryDayBean>() {
            @Override
            public void onSuccess(EveryDayBean value) {
                if (value.getInfo() != null) {
                    cardView.setVisibility(View.VISIBLE);
                    dataList.addAll(value.getInfo());
                    adapter.notifyDataSetChanged();
                }
            }
        });

    }*/

    private void initView() {

        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        dataList = new ArrayList<>();
        adapter = new CommonAdapter<EveryDayBean.InfoBean>(this, R.layout.order_detail_item, dataList) {
            @Override
            protected void convert(ViewHolder holder, EveryDayBean.InfoBean infoBean, int position) {

                SuperTextView superTextView = (SuperTextView) holder.getView(R.id.suerPerTv);
                superTextView.setLeftString(infoBean.getTime());
//                superTextView.setCenterString(repaymentBean.getType() == 1 ? "还款" : "逾期");
//                superTextView.setRightString("¥" + repaymentBean.getMoney());

                superTextView.setCenterString("¥" + infoBean.getMoney());
                holder.setOnClickListener(R.id.btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String type = "1";
                        getPartMoney(type);
                    }
                });

            }


        };
        recyclerview.setAdapter(adapter);


    }

    private void loadData() {
        multipleStatusView.showLoading();
        RetrofitManager.create().order_info(SPUtils.getInstance().getString("uid"), order_id)
                .compose(this.<OrderDetailBean>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonObserver<OrderDetailBean>(multipleStatusView) {
                    @Override
                    public void onSuccess(OrderDetailBean value) {
                        if (value.getCode() == Constant.CODE_SUCC) {
                            mValue = value;
                            goodTitle.setText(value.getGoods().getGoods_name());
                            //最迟还款日
                            time.setText(value.getTime());
                            time.setTextColor(getResources().getColor(R.color.colorPrimary));
                            //商品金额
                            goodMoney.setText(value.getGoods().getMoney());
                            Glide.with(BillDetailActivity.this).load(Constant.IMAGE_PATH + value.getGoods().getImg()).into(goodImage);
                            hkzr.setText(value.getStage() + "天");
                            moneyall.setText("¥" + value.getMoney_all());
                            yiyuqi.setText(value.getStateString());

                            timeTips.setText("购买日期");
                            timeTips.setTextColor(getResources().getColor(R.color.textColorDark));


                            if ("2".equals(payType)) {
                                //如果当前订单是支付宝支付
                                abc.setVisibility(View.GONE);
                                huankuan.setVisibility(View.GONE);
                                yiyuqi.setVisibility(View.GONE);
                                eft.setVisibility(View.GONE);

                            } else {
                                //不做任何处理
                            }


                            if (value.getState() == 1) {
                                //还款状态
                            } else if (value.getState() == 2) {
                                huankuan.setEnabled(false);
                                ToastUtils.showShort("已还清");
                                //已还清
                            } else {
                                //已逾期
                                yuqiTips.setVisibility(View.VISIBLE);
                            }


                        }
                    }
                });

    }

    @Override
    public int getContentView() {
        return R.layout.activity_bill_detail;
    }


    private void getPartMoney(final String type) {
        prompDialog.showLoading("请等待");
        DataResponsibility
                .getInstance()
                .getPartMoney(mValue.getStage_id(), type, this.<GetPartMoneyBean>bindToLifecycle())
                .flatMap(new Function<GetPartMoneyBean, Observable<ReBean>>() {
                    @Override
                    public Observable<ReBean> apply(GetPartMoneyBean getPartMoneyBean) throws Exception {
                        return DataResponsibility
                                .getInstance()
                                .alipay_repayment(mValue.getStage_id(), type, BillDetailActivity.this.<ReBean>bindToLifecycle(), getPartMoneyBean.getShould_money());
                    }
                })
                .subscribe(new CommonObserver<ReBean>(prompDialog) {
                    @Override
                    public void onSuccess(ReBean value) {
                        if (value.getInfo() != null && !TextUtils.isEmpty(value.getInfo().getStr())) {
                            prompDialog.dismiss();
                            String re = value.getInfo().getStr();
                            aliPay(re);
                        } else {


                            prompDialog.showError("加载失败,请重试");
                        }
                    }
                });
    }

    private void aliPay(String re) {
        //1.创建支付宝支付订单的信息
        String rawAliOrderInfo = re;

        //3.发送支付宝支付请求
        AliPayReq2 aliPayReq = new AliPayReq2.Builder()
                .with(this)//Activity实例
                .setRawAliPayOrderInfo(rawAliOrderInfo)//支付宝支付订单信息
                .create()
                .setOnAliPayListener(null);//
        PayAPI.getInstance().sendPayRequest(aliPayReq);

        //关于支付宝支付的回调
        aliPayReq.setOnAliPayListener(new AliPayReq2.OnAliPayListener() {
            @Override
            public void onPaySuccess(String resultInfo) {


            }

            @Override
            public void onPayFailure(String resultInfo) {

            }

            @Override
            public void onPayConfirmimg(String resultInfo) {

            }

            @Override
            public void onPayCheck(String status) {

            }
        });

    }

    public static void open(String order_id) {
        Bundle extras = new Bundle();
        extras.putString("order_id", order_id);
        ActivityUtils.startActivity(extras, BillDetailActivity.class);
    }

    public static void open(String order_id, String title, String payType) {
        Bundle extras = new Bundle();
        extras.putString("order_id", order_id);
        extras.putString("title", title);
        extras.putString("payType", payType);
        ActivityUtils.startActivity(extras, BillDetailActivity.class);
    }

    @OnClick(R.id.huankuan)
    public void onViewClicked(View view) {

        if (mValue == null) {
            ToastUtils.showShort("数据请求有误");
            return;
        }
        String type = "";
        switch (view.getId()) {
            case R.id.huankuan:
                type = "1";
                getPartMoney(type);
                break;
            /*case R.id.btnRight:
                type = "2";
                getPartMoney(type);
                break;*/
        }
    }
}
